import React, { ChangeEvent, useContext, useReducer, useState } from 'react'
import reducer from './reducer'
import initialState from './store'
import { nanoid } from 'nanoid'
import { TodoContext } from './index'

const InputForm: React.FC = () => {
  const [value, setValue] = useState('')
  const { todoList, dispatch } = useContext(TodoContext)

  function add(e: ChangeEvent<HTMLFormElement>) {
    e.preventDefault()
    if (!value.trim()) return

    dispatch({
      type: 'add',
      payload: { id: nanoid(5), title: value },
    })

    setValue('')
  }

  function handleChange(e: ChangeEvent<HTMLInputElement>) {
    setValue(e.target.value)
  }

  return (
    <>
      <hr />
      <p>InputForm</p>
      <div>
        <form onSubmit={add}>
          <input type="text" value={value} onChange={handleChange} />
          <button type="submit">确定 # {todoList.length}</button>
        </form>
      </div>
    </>
  )
}

export default InputForm
